package net.lcheng.shop.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.lcheng.model.*;
import net.lcheng.service.*;
import net.lcheng.shop.vo.CurrentUserModel;
import net.lcheng.shop.vo.ShippingAddressModel;
import net.lcheng.utils.Oorder2OrderModel;
import net.lcheng.vo.OrderModel;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.*;

/**
 * Created by LV on 2016/7/15.
 */
@Controller
@RequestMapping("/shopping")
public class ShoppingController {

    @Autowired
    private ShoppingService shoppingService;
    @Autowired
    private ProductService productService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserShippingAddressService shippingAddressService;
    @Autowired
    private OOrderService orderService;
    @Autowired
    private AreasService areasService;
    @Autowired
    private TradeManageService tradeManageService;

    /**
     * 添加商品到购物车
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addGoodsToCart",method = RequestMethod.POST)
    public String addGoodsToCart(@RequestParam("pid") String productId){
        Subject currentUser= SecurityUtils.getSubject();
        Map<String,String> map=new HashMap<>();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
            //获取要发布的商品信息
            PProduct product = productService.getProductByPrimaryKey(productId);
            //添加到购物车
            if (product != null&&user!=null) {
                UserShoppingCart cart = new UserShoppingCart();
                cart.setShopId(product.getWxShopShopId());//商品id
                cart.setUserUserId(user.getUserId());//买家的userId
                cart.setProductNum(1);//添加购物车，一次添加一个
                cart.setCartId(UUID.randomUUID().toString());//购物车主键
                cart.setProductId(product.getProductId());//商品Id
                cart.setProductImage(product.getProductMainImage());//商品的主图片
                cart.setProductName(product.getProductName());//商品名称
                cart.setProductPrice(product.getSalePrice());//商品的价格
                cart.setProductSku("");//TODO 暂时为空
                cart.setProductAttribute("");//TODO 暂时为空，发布产品添加属性时再添加
                cart.setCreateOn(new Date());
                int status = shoppingService.addGoodsToCart(cart);
                switch (status) {
                    case 0:
                        map.put("status", "s0");//添加失败
                        break;
                    case 1:
                        map.put("status", "s1");//添加成功
                        break;
                    case 2:
                        map.put("status", "s2");//添加成功（添加了购物车里相同的商品）
                        break;
                }
                return JSON.toJSONString(map);
            }
            map.put("status","error");
            return JSON.toJSONString(map);
        }
        //看是否授权，没有授权返回一个登陆的url,在js中做跳转
        map.put("url","login");
        return JSON.toJSONString(map);
    }

    /**
     * 立即购买
     * @return
     */
    @RequestMapping(value = "/buyGoodsAtOnce")
    public String buyGoodsAtOnce(Model model, @RequestParam("pid") String productId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
            if (productId!=null) {
                //获取产品信息
                PProduct product = productService.getProductByPrimaryKey(productId);

                if (user!=null&&product!=null){
                    //转换成购物车对象，在购物车结算时也用到这个页面，复用这个页面
                    UserShoppingCart cart=new UserShoppingCart();
                    cart.setProductId(product.getProductId());//产品ID
                    cart.setProductName(product.getProductName());//产品名
                    cart.setProductImage(product.getProductMainImage());//产品图片
                    cart.setProductPrice(product.getSalePrice());//产品价格
                    cart.setProductAttribute("");//产品属性暂时为空 TODO
                    cart.setProductSku("");//产品sku暂时为空
                    cart.setProductNum(1);//立即购买下单只有一个商品
                    List<UserShoppingCart> list=new ArrayList<>();
                    list.add(cart);
                    model.addAttribute("cartList",list);

                    //计算商品总价
                    double totalPayment=product.getSalePrice().doubleValue()+product.getFreight().doubleValue();
                    model.addAttribute("totalPayment",totalPayment);
                    //邮费
                    model.addAttribute("freight",product.getFreight());

                    //查看该用户是否设置了默认的收货地址
                    UserShippingAddress shippingAddress=shippingAddressService.getShippingAddressByUserIdAndDefaultType(user.getUserId());
                    if (shippingAddress!=null)
                        model.addAttribute("shippingAddress",shippingAddress);
                    else model.addAttribute("shippingAddress",null);

                    return "shopping/settle_account_at_once";
                }
                return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 结算(立即购买)
     * @return
     */
    @RequestMapping(value = "/settleAccount")
    public String settleAccount(Model model,@RequestParam("aid") String addressId,@RequestParam("pid") String productId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                //获取产品信息
                PProduct product=productService.getProductByPrimaryKey(productId);
                UserShoppingCart cart=new UserShoppingCart();
                cart.setProductId(product.getProductId());//产品ID
                cart.setProductName(product.getProductName());//产品名
                cart.setProductImage(product.getProductMainImage());//产品图片
                cart.setProductPrice(product.getSalePrice());//产品价格
                cart.setProductAttribute("");//产品属性暂时为空 TODO
                cart.setProductSku("");//产品sku暂时为空
                cart.setProductNum(1);//立即购买下单只有一个商品
                List<UserShoppingCart> list=new ArrayList<>();
                list.add(cart);

                String orderId=shoppingService.settleAccount(product.getWxShopShopId(),user.getUserId(),addressId,list);

                if (orderId!=null&&!orderId.equals("")) {
                    //查询订单信息
                    OOrder order=orderService.getOOrderByOrderId(orderId);
                    //解析订单商品的Json串,
                    OrderModel orderModel= Oorder2OrderModel.getOorder2OrderModel(order);
                    model.addAttribute("orderModel",orderModel);
                    return "/shopping/checkout_counter";

            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 添加收货地址
     * @return
     */
    @RequestMapping(value = "/addShippingAddress",method = RequestMethod.GET)
    public String addShippingAddress(Model model,@RequestParam("pid") String productId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user!=null){
                    //获取该用户的所有收货地址
                    List<UserShippingAddress> addressList=shippingAddressService.getUserShippingAddressByUserUserId(user.getUserId());
                    model.addAttribute("addressList",addressList);
                    model.addAttribute("productId",productId);
                }
                return "/shopping/add_shipping_address";

        }
        return "redirect:/login";
    }

    /**
     * 用户添加新的收获地址
     * @return
     */
    @RequestMapping(value = "/insertShippingAddress",method = RequestMethod.GET)
    public String insertShippingAddress(Model model,@RequestParam("pid") String productId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (productId!=null) {
                model.addAttribute("productId",productId);
                return "/shipping_address/shipping_address_add";
            }
            return "redirect:/error";
        }
       return "redirect:/login";
    }

    /**
     * 异步获取省市区列表
     * @param parentCode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAreasByParentCode",method = RequestMethod.GET)
    public String getAreasByParentCode(@RequestParam("pcid") String parentCode){
        Subject currentUser= SecurityUtils.getSubject();
        Map<String,Object> map=new HashMap<>();
        if (currentUser.isAuthenticated()) {
            if (parentCode!=null){
                if (parentCode.equals("no"))
                        parentCode="";
                //获取省市区列表
                List<BaseAreas> areasList=areasService.findAreasListByParentCode(parentCode);
                map.put("areaList",areasList);
                return JSON.toJSONString(map);
            }
            map.put("areaList",null);
            return JSON.toJSONString(map);
        }
        map.put("url","login");
        return JSON.toJSONString(map);
    }

    /**
     * 保存用户添加的收货地址
     * @param productId 立即购买的产品Id
     * @return String
     */
    @RequestMapping(value = "/savingInsertShippingAddress",method = RequestMethod.POST)
    public String savingInsertShippingAddress(String productId, @Valid ShippingAddressModel addressModel, BindingResult result){
        if (result.hasErrors())
            return "redirect:/shopping/insertShippingAddress?pid="+productId;
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user!=null) {
                    //保存收货地址
                    UserShippingAddress address=new UserShippingAddress();
                    String aid=UUID.randomUUID().toString();//在重定向地址中会使用到
                    address.setAddressId(aid);//主键
                    address.setUserUserId(user.getUserId());//用户Id
                    address.setConsigneeName(addressModel.getName());
                    address.setConsigneePhone(addressModel.getPhone());
                    address.setProvinceCode(addressModel.getProvinceCode());
                    address.setProvinceName(addressModel.getProvinceName());
                    address.setCityCode(addressModel.getCityCode());
                    address.setCityName(addressModel.getCityName());
                    address.setDistrictCode(addressModel.getDistrictCode());
                    address.setDistrictName(addressModel.getDistrictName());
                    address.setAddress(addressModel.getAddress());
                    address.setIsDefault(0);
                    address.setCreateOn(new Date());

                    int status=shippingAddressService.insertShippingAddress(address);
                    if (status>0)
                        //return "redirect:/shopping/addShippingAddress?pid=" + productId;//重定向到选择地址页面
                        return "redirect:/shopping/savingShippingAddress?pid="+productId+"&aid="+aid;
                    else
                        return "redirect:/error";
                }
                return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 保存收货地址（立即购买）
     * @param addressId 地址id
     * @param productId 购买的产品id
     * @return String
     */
    @RequestMapping(value = "/savingShippingAddress")
    public String savingShippingAddress(Model model,@RequestParam("aid") String addressId,@RequestParam("pid") String productId) {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
            if (productId != null) {
                //获取产品信息
                PProduct product = productService.getProductByPrimaryKey(productId);

                if (user != null && product != null) {
                    //转换成购物车对象，在购物车结算时也用到这个页面，复用这个页面
                    UserShoppingCart cart = new UserShoppingCart();
                    cart.setProductId(product.getProductId());//产品ID
                    cart.setProductName(product.getProductName());//产品名
                    cart.setProductImage(product.getProductMainImage());//产品图片
                    cart.setProductPrice(product.getSalePrice());//产品价格
                    cart.setProductAttribute("");//产品属性暂时为空 TODO
                    cart.setProductSku("");//产品sku暂时为空
                    cart.setProductNum(1);//立即购买下单只有一个商品
                    List<UserShoppingCart> list = new ArrayList<>();
                    list.add(cart);
                    model.addAttribute("cartList", list);

                    //计算商品总价
                    double totalPayment = product.getSalePrice().doubleValue() + product.getFreight().doubleValue();
                    model.addAttribute("totalPayment", totalPayment);
                    //邮费
                    model.addAttribute("freight", product.getFreight());

                    //查看该用户是否设置了默认的收货地址
                    UserShippingAddress shippingAddress = shippingAddressService.getShippingAddressByPrimaryKey(addressId);
                    if (shippingAddress != null)
                        model.addAttribute("shippingAddress", shippingAddress);
                    else model.addAttribute("shippingAddress", null);

                    model.addAttribute("productId",productId);

                    return "shopping/settle_account_address_at_once";
                }
                return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 更改收货地址（立即购买）
     * @param addressId 收货地址ID
     * @param productId 立即购买的商品ID
     * @return
     */
    @RequestMapping(value = "/editShippingAddress",method = RequestMethod.GET)
    public String editShippingAddress(Model model,@RequestParam("aid") String addressId,@RequestParam("pid") String productId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (addressId!=null&&productId!=null) {
                //查找要更改的收货地址
                UserShippingAddress shippingAddress=shippingAddressService.getShippingAddressByPrimaryKey(addressId);
                model.addAttribute("shippingAddress",shippingAddress);
                model.addAttribute("productId",productId);
                return "/shipping_address/shipping_address_edit";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 保存更改的收货地址（立即购买）
     * @param addressModel 收货地址的表单数据
     * @param productId 立即购买的商品Id
     * @return
     */
    @RequestMapping(value = "/savingEditShippingAddress",method = RequestMethod.POST)
    public String savingEditShippingAddress(@Valid ShippingAddressModel addressModel,String productId,String addressId,BindingResult result){
        if (result.hasErrors())
            return "redirect:/shopping/editShippingAddress?aid="+addressId+"&pid="+productId;
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (addressModel!=null&&productId!=null&&addressId!=null) {
                UserShippingAddress address=new UserShippingAddress();
                address.setAddressId(addressId);
                address.setConsigneeName(addressModel.getName());
                address.setConsigneePhone(addressModel.getPhone());
                address.setProvinceName(addressModel.getProvinceName());
                address.setProvinceCode(addressModel.getProvinceCode());
                address.setCityName(addressModel.getCityName());
                address.setCityCode(addressModel.getCityCode());
                address.setDistrictName(addressModel.getDistrictName());
                address.setDistrictCode(addressModel.getDistrictCode());
                address.setAddress(addressModel.getAddress());
                if (addressModel.getIsDefault()!=null&&addressModel.getIsDefault().equals("on"))
                    address.setIsDefault(1);
                else address.setIsDefault(0);

                int status=shippingAddressService.editShippingAddressByPrimaryKey(address);
                if (status>0)
                    return "redirect:/shopping/addShippingAddress?pid=" + productId;
                else return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 删除收货地址（立即购买）
     * @param productId
     * @return
     */
    @RequestMapping(value = "/deleteShippingAddress",method = RequestMethod.GET)
    public String deleteShippingAddress(@RequestParam("aid") String addressId,@RequestParam("pid") String productId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (addressId!=null&&productId!=null) {
                int status=shippingAddressService.deleteAddress(addressId);
                if (status>0) {
                    return "redirect:/shopping/addShippingAddress?pid=" + productId;
                }else
                    return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 我的购物车
     * @param shopId
     * @return
     */
    @RequestMapping(value = "/myShoppingCart")
    public String myShoppingCart(Model model,@RequestParam("sid") int shopId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user!=null){
                    List<UserShoppingCart> cartList=shoppingService.getCartByUserIdAndShopId(user.getUserId(),shopId);
                    model.addAttribute("cartList",cartList);
                    model.addAttribute("shopId",shopId);
                    return "/shopping/shopping_cart";
                }
                return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 结算购物车
     * @param carts
     * @return
     */
    @RequestMapping(value = "/settleAccountCart",method = RequestMethod.POST)
    public String settleAccountCart(Model model,String[] carts,int shopId){
        if (carts==null){
            return "redirect:/shopping/myShoppingCart?sid="+shopId;
        }
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user!=null) {
                    //结算购物车列表
                    List<UserShoppingCart> cartList = new ArrayList<>();
                    //商品总价
                    double totalPayment=0.0;
                    double totalFreight=0.0;
                    //结算购物车的里商品的id组合
                    String cartIdString="";

                    for (String cartId : carts) {
                        UserShoppingCart cart = shoppingService.getCartByPrimaryKey(cartId);
                        cartList.add(cart);
                        //cartId组合
                        cartIdString+=(cartId+"|");
                        //商品总价
                        totalPayment+=(cart.getProductPrice().doubleValue()*cart.getProductNum());
                        //邮费
                        PProduct product=productService.getProductByPrimaryKey(cart.getProductId());
                        totalFreight+=product.getFreight().doubleValue()*cart.getProductNum();

                    }
                    model.addAttribute("cartList", cartList);

                    model.addAttribute("totalPayment",totalPayment+totalFreight);
                    //邮费
                    model.addAttribute("freight",totalFreight);
                    //将传递的参数做一下处理
                    String cartIdStringTmp=cartIdString.substring(0,cartIdString.lastIndexOf('|'));
                    model.addAttribute("cartIdString",cartIdStringTmp);

                    //查看该用户是否设置了默认的收货地址
                    UserShippingAddress shippingAddress=shippingAddressService.getShippingAddressByUserIdAndDefaultType(user.getUserId());
                    if (shippingAddress!=null)
                        model.addAttribute("shippingAddress",shippingAddress);
                    else model.addAttribute("shippingAddress",null);

                    return "/shopping/settle_account_cart";
                }
                return "redirect:error";
        }
        return "redirect:/login";
    }

    /**
     * 添加收货地址(购物车结算)
     * @return
     */
    @RequestMapping(value = "/addShippingAddressCart",method = RequestMethod.GET)
    public String addShippingAddressCart(Model model,@RequestParam("cs") String CartIdString){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user!=null){
                    //获取该用户的所有收货地址
                    List<UserShippingAddress> addressList=shippingAddressService.getUserShippingAddressByUserUserId(user.getUserId());
                    model.addAttribute("addressList",addressList);
                    model.addAttribute("cartId",CartIdString);
                }
                return "/shopping/add_shipping_address_cart";
        }
        return "redirect:/login";
    }

    /**
     * 添加新的收货地址（购物车）
     * @param model
     * @param cartIdString 购物车选择的列表id组合
     * @return
     */
    @RequestMapping(value = "/insertShippingAddressCart",method = RequestMethod.GET)
    public String insertShippingAddressCart(Model model,@RequestParam("cs") String cartIdString){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (cartIdString!=null) {
                model.addAttribute("cartIdString",cartIdString);
                return "/shipping_address/shipping_address_add_cart";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 保存新添加的收货地址（购物车）
     * @param addressModel 收货地址model
     * @param cartIdString 购物车商品的主键组合
     * @param result 验证结果
     * @return String
     */
    @RequestMapping(value = "/savingInsertShippingAddressCart",method = RequestMethod.POST)
    public String savingInsertShippingAddressCart(@Valid ShippingAddressModel addressModel,String cartIdString,BindingResult result){
        if (result.hasErrors()) {
            //重定向需要替换，不然出现非法参数
            String replace = cartIdString.replace("|", "%7c");
            return "redirect:/shopping/insertShippingAddressCart?cs=" + replace;
        }
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
            if (addressModel!=null&&user!=null) {
                    //保存收货地址
                    UserShippingAddress address = new UserShippingAddress();
                    String aid=UUID.randomUUID().toString();//在重定向时需要用到
                    address.setAddressId(aid);//主键
                    address.setUserUserId(user.getUserId());//用户Id
                    address.setConsigneeName(addressModel.getName());
                    address.setConsigneePhone(addressModel.getPhone());
                    address.setProvinceCode(addressModel.getProvinceCode());
                    address.setProvinceName(addressModel.getProvinceName());
                    address.setCityCode(addressModel.getCityCode());
                    address.setCityName(addressModel.getCityName());
                    address.setDistrictCode(addressModel.getDistrictCode());
                    address.setDistrictName(addressModel.getDistrictName());
                    address.setAddress(addressModel.getAddress());
                    address.setIsDefault(0);
                    address.setCreateOn(new Date());

                    int status=shippingAddressService.insertShippingAddress(address);
                    if (status>0) {
                        //重定向需要替换，不然出现非法参数
                        String replace = cartIdString.replace("|", "%7c");
//                        return "redirect:/shopping/addShippingAddressCart?cs=" + replace;//重定向到添加地址
                        return "redirect:/shopping/savingAddShippingAddressCart?cs="+replace+"&aid="+aid;
                    }
                    else
                        return "redirect:/error";
                }
                return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 编辑用户收货地址（购物车）
     * @param addressId  需要修改的收货地址Id
     * @param cartIdString 购物车选中Id组合
     * @return
     */
    @RequestMapping(value = "/editShippingAddressCart",method = RequestMethod.GET)
    public String editShippingAddressCart(Model model,@RequestParam("aid") String addressId,@RequestParam("cs") String cartIdString){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (addressId!=null&&cartIdString!=null){
                //收货地址信息
                UserShippingAddress shippingAddress=shippingAddressService.getShippingAddressByPrimaryKey(addressId);
                model.addAttribute("shippingAddress",shippingAddress);
                model.addAttribute("cartIdString",cartIdString);
                return "/shipping_address/shipping_address_edit_cart";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 保存更改的收货地址（购物车）
     * @param addressModel 收货地址vo
     * @param addressId 修改的地址Id
     * @param cartIdString 选择的购物车列表id组合
     * @return
     */
    @RequestMapping(value = "/savingEditShippingAddressCart",method = RequestMethod.POST)
    public String savingEditShippingAddressCart(@Valid ShippingAddressModel addressModel, String addressId, String cartIdString,BindingResult result){
        if (result.hasErrors()) {
            String replace = cartIdString.replace("|", "%7c");
            return "redirect:/shopping/editShippingAddressCart?aid=" + addressId + "&cs=" + replace;
        }
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (addressModel!=null&&addressId!=null&&cartIdString!=null){
                //保存修改
                UserShippingAddress address=new UserShippingAddress();
                address.setAddressId(addressId);
                address.setConsigneeName(addressModel.getName());
                address.setConsigneePhone(addressModel.getPhone());
                address.setProvinceName(addressModel.getProvinceName());
                address.setProvinceCode(addressModel.getProvinceCode());
                address.setCityName(addressModel.getCityName());
                address.setCityCode(addressModel.getCityCode());
                address.setDistrictName(addressModel.getDistrictName());
                address.setDistrictCode(addressModel.getDistrictCode());
                address.setAddress(addressModel.getAddress());
                if (addressModel.getIsDefault()!=null&&addressModel.getIsDefault().equals("on"))
                    address.setIsDefault(1);
                else address.setIsDefault(0);

                int status=shippingAddressService.editShippingAddressByPrimaryKey(address);

                if (status>0) {
                    //重定向需要替换，不然出现非法参数
                    String replace = cartIdString.replace("|", "%7c");
                    return "redirect:/shopping/addShippingAddressCart?cs=" + replace;
                }
                else
                    return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 删除收货地址（购物车）
     * @param addressId 要删除的地址Id
     * @param cartIdString 选择的购物车列表id组合
     * @return
     */
    @RequestMapping(value = "/deleteShippingAddressCart",method = RequestMethod.GET)
    public String deleteShippingAddressCart(@RequestParam("aid") String addressId,@RequestParam("cs") String cartIdString){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (addressId!=null&&cartIdString!=null) {
                int status=shippingAddressService.deleteAddress(addressId);
                if (status>0) {
                    //不替换会出现参数非法
                    String replace = cartIdString.replace("|", "%7c");
                    return "redirect:/shopping/addShippingAddressCart?cs=" + replace;
                }
                else
                    return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }


    /**
     * 保存收货地址（购物车结算）
     * @return
     */
    @RequestMapping(value = "/savingAddShippingAddressCart")
    public String savingAddShippingAddressCart(Model model,@RequestParam("cs") String cartIdString,@RequestParam("aid") String addressId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
            if (user != null) {
                if (cartIdString!=null&&addressId!=null){
                    List<UserShoppingCart> list=new ArrayList<>();

                    String[] carts=cartIdString.split("\\|");
                    double freight=0.0;
                    double totalPayment=0.0;
                    for (String cartId:carts){
                        UserShoppingCart cart=shoppingService.getCartByPrimaryKey(cartId);
                        //产品信息
                        if (cart!=null) {
                            PProduct product = productService.getProductByPrimaryKey(cart.getProductId());
                            //运费总价
                            freight += product.getFreight().doubleValue() * cart.getProductNum();
                            //商品总价
                            totalPayment += (cart.getProductPrice().doubleValue() * cart.getProductNum());
                        }
                        list.add(cart);
                    }
                    model.addAttribute("cartList",list);
                    //总运费
                    model.addAttribute("freight",freight);
                    //实际支付
                    model.addAttribute("totalPayment",totalPayment+freight);
                    //收货地址
                    UserShippingAddress shippingAddress=shippingAddressService.getShippingAddressByPrimaryKey(addressId);
                    model.addAttribute("shippingAddress",shippingAddress);

                    model.addAttribute("cartIdString",cartIdString);

                    return "/shopping/settle_account_address_cart";
                }
                return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 购物车结算
     * @return
     */
    @RequestMapping(value = "/settleAccountCart")
    public String settleAccountCart(Model model,@RequestParam("cs") String cartIdString,@RequestParam("aid") String addressId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user!=null) {
                    if (cartIdString != null && addressId != null) {
                        List<UserShoppingCart> list = new ArrayList<>();

                        String[] carts = cartIdString.split("\\|");
                        //商店Id
                        int shopId = 0;
                        for (String cartId : carts) {
                            UserShoppingCart cart = shoppingService.getCartByPrimaryKey(cartId);
                            //产品信息
                            PProduct product = productService.getProductByPrimaryKey(cart.getProductId());
                            shopId = product.getWxShopShopId();
                            //运费总价
                            list.add(cart);
                        }
                        //结算
                        String orderId = shoppingService.settleAccount(shopId, user.getUserId(), addressId, list);

                        if (orderId!=null&&!orderId.equals("")) {
                            //清除已生成订单的购物车商品
                            shoppingService.deleteCartProduct(list);
                            //获取订单信息
                            OOrder order=orderService.getOOrderByOrderId(orderId);
                            OrderModel orderModel= Oorder2OrderModel.getOorder2OrderModel(order);
                            model.addAttribute("orderModel",orderModel);
                            return "/shopping/checkout_counter";
                        }
                        else
                            return "redirect:/error";
                    }
                    return "redirect:/error";
            }
        return "redirect:/error";
    }
        return "redirect:/login";
    }

    /**
     * 异步获取购物车商品信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getCartItem")
    public String getCartItem(@RequestParam("cid") String cartId){
        Subject currentUser = SecurityUtils.getSubject();
        Map<String,Object> map=new HashMap<>();
        if (currentUser.isAuthenticated()) {
            if (cartId!=null) {
                UserShoppingCart cart = shoppingService.getCartByPrimaryKey(cartId);
                map.put("cart",cart);
                return JSON.toJSONString(map);
            }
            map.put("cart",null);
            return JSON.toJSONString(map);
        }
        map.put("url","login");
        return JSON.toJSONString(map);
    }

    /**
     * 用户支付
     * @param orderId 要支付的订单Id
     * @return String
     */
    @RequestMapping(value = "/settleAccountByUser",method = RequestMethod.GET)
    public String settleAccountByUser(Model model,@RequestParam("oid") String orderId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            model.addAttribute("orderId",orderId);
            return "/shopping/settle_account_order";
        }
        return "redirect:/login";
    }

    /**
     * 完成支付
     * @return
     */
    @RequestMapping(value = "/applySettleAccount",method = RequestMethod.GET)
    public String applySettleAccount(Model model,@RequestParam("oid") String orderId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //暂时模拟完成支付 todo
            OOrder order = tradeManageService.getOrderByPrimaryKey(orderId);
            if (order != null) {
                order.setOrderStatus(1);//已支付状态
                order.setPaymentStatus(2);
                //更新为已支付状态
                int status = shoppingService.paymentByBuyer(order);
                if (status > 0) {
                    model.addAttribute("order", order);
                    return "/user_order/payment_success";
                } else
                    return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

}
